<?php

namespace App\Templates;

use App\Models\MLog;
use App\Models\MUser;
use DB;
use Exception;


/**
 * 删除未激活会员的请求处理
 */
trait DelUserAct
{
    public function delUserAct($id, $in_token = null)
    {
        $user = MUser::find($id);

        if (empty($user)) {
            $this->data = $this->makeJsCode(1, "要删除的用户不存在！");
            return back()->with($this->data);
        }

        if ($user->ok_status == MUser::$STATUS_ACTIVATED) {
            $this->data = $this->makeJsCode(1, "已激活用户不可删除！");
            return back()->with($this->data);
        }

        if ($user->bdzx != ss('uid')) {
            $this->data = $this->makeJsCode(1, "您无权删除此会员！");
            return back()->with($this->data);
        }

        try {
            DB::transaction(function () use ($user, $in_token) {
                //删除未激活用户，写入系统日志，删除用户钱包，删除用户业绩记录
                if ($user->delUser()) {

                    $this->data = $this->makeJsCode(0, "删除成功！");

                    if ($in_token == env("IN_USER_TOKEN")) {
                        MLog::log("后台删除了未激活用户 $user->username ( ID: $user->id ) !");
                    }

                } else {
                    DB::rollBack();
                    $this->data = $this->makeJsCode(1, "删除失败！");
                }
            });
        } catch (Exception $e) {
            $this->data = $this->makeJsCode(1, "删除失败！");
        }

        return back()->with($this->data);
    }
}